#include "thread.h"
#include "mutex.h"
#include "autolock.h"

namespace log4x
{
void* 
Thread::entry(void* data, int id)
{
    Thread *trd = (Thread *)data;
    {
        AutoLock locker(trd->m_mtx);
    }

    if (trd->m_func)
    {
        trd->m_func(trd->m_data, id);
    }
    else
    {
        trd->run();
    }

    return NULL;
}

Thread::Thread()
{
    m_trd    = 0;
    m_func   = NULL;
    m_data   = NULL;
    m_id     = -1;
    m_active = false;
}

Thread::~Thread()
{
}

void
Thread::setEntry(routine func, void*  data, int id)
{
    m_func = func;
    m_data = data;
    m_id   = id;
}

int
Thread::start()
{
    AutoLock locker(m_mtx);
    if (m_active)
    {
        return 0;
    }

    m_trd = os::thread()->start(entry, this, m_id);
    if (!m_trd)
    {
        return -1;
    }
    m_active = true;

    return 0;
}

void
Thread::stop()
{
    {
        AutoLock locker(m_mtx);
        m_active = false;
    }

    os::thread()->end(m_trd);
}

void
Thread::detach()
{
    os::thread()->detach(m_trd);
}

bool
Thread::active()
{
    return m_active;
}

void
Thread::run()
{}

void
Thread::sleep(int ms, int per)
{
    int m_per = per;
    if (m_per > ms)
    {
        m_per = ms;
    }

    int left = ms;
    while (active() && left > 0)
    {
        os::thread()->sleep(m_per);
        left -= m_per;
    }
}
}
